<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <el-select
          v-model="form.status"
          placeholder="状态"
          style="width: 100px"
          clearable
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-input
          v-model="form.name"
          style="width: 200px"
          clearable
          placeholder="角色名称"
        ></el-input>
        <VGroup>
          <el-select v-model="form.dateRange.type" style="width: 100px">
            <el-option label="创建时间" value="create_time"></el-option>
            <el-option label="修改时间" value="update_time"></el-option>
          </el-select>
          <el-date-picker
            v-model="form.dateRange.value"
            clearable
            type="datetimerange"
            range-separator="至"
            start-placeholder="00:00:00"
            end-placeholder="23:59:59"
            style="width: 400px"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <el-button type="primary" @click="handleAdd(null)" v-hasPermi="[personnelAuthList.role.add]">
          <SvgIcon icon-class="Plus" class="text-[12px] mr-[6px]"/>新增
        </el-button>
        <el-button @click="handleCopy" v-hasPermi="[personnelAuthList.role.copy]"> <SvgIcon icon-class="copy" class="text-[12px] mr-[6px]"/>复制 </el-button>
        <el-button @click="handleDelete" v-hasPermi="[personnelAuthList.role.delete]">
          <template #icon>
            <SvgIcon icon-class="del"></SvgIcon>
          </template>
          删除
        </el-button>
      </template>
    </VTable>
  </VPage>
  <VUserManage
    v-model="userVisible"
    :data="userData"
    :api="userApi"
    @close="userData = {}"
    @refresh="refresh"
  ></VUserManage>
  <VRole
    ref="roleRef"
    content="角色"
    :title="optionsType"
    @confirm="roleConfirm"
  >
  </VRole>
  <VLog ref="logRef" :api="getRoleLog"></VLog>
</template>
<script setup lang="jsx">
import SvgIcon from "@/components/SvgIcon/index.vue";
import { ElMessage } from "element-plus";
import { statusOptions } from "@/data/index.js";
import { defaultTime } from "./data.js";
import VRole from "@/components/VRole";
import VLog from "@/components/VLog";
import {
  role,
  status,
  create,
  detail,
  copyAdd,
  deleteR,
  updateRole,
  getUsersList,
  getRoleLog,
  setUser,
} from "./api";
import VUserManage from "@/components/VUserManage";
import { personnelAuthList } from "@/Auth/personnel.js";
import { isPermission } from "@/hooks/permission.js";
const { proxy } = getCurrentInstance();
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      status: "",
      name: "",
      dateRange: { type: "create_time", value: [], range: true }, // 组合+日期范围
    },
  },
  columns: [
    { type: "checkbox", width: "60" },
    { field: "id", title: "ID", width: "60" },
    { field: "name", title: "角色名称", minWidth: "200" },
    { field: "create_time", title: "创建时间", minWidth: "200" },
    { field: "create_user_text", title: "创建人", minWidth: "200" },
    {
      field: "status_text",
      title: "状态",
      minWidth: "100",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div
                onClick={() => handleSwitch(row)}
                style="display: inline-block;"
              >
                <el-switch
                  v-model={row.status}
                  active-value={1}
                  inactive-value={0}
                ></el-switch>
              </div>
            </div>
          );
        },
      },
    },
    { field: "update_user_text", title: "修改人", minWidth: "200" },
    {
      title: "操作",
      fixed: "right",
      width: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {isPermission([personnelAuthList.role.edit]) && (
                <el-button
                  type="primary"
                  link
                  onClick={() => handleAdd(row.id)}
                >
                  编辑
                </el-button>
              )}
              {isPermission([personnelAuthList.role.manage_people]) && (
                <el-button
                  type="primary"
                  onClick={() => handleUesrManage(row)}
                  link
                >
                  分配人员
                </el-button>
              )}
              <el-button type="primary" onClick={() => handleLog(row.id)} link>
                日志
              </el-button>
            </div>
          );
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        return role({ ...form, ...page });
      },
    },
  },
});
//状态修改
const handleSwitch = async (val) => {
  const { code, message } = await status({ id: val.id });
  if (code !== 200) return ElMessage.error(message);
  ElMessage.success("更新成功!");
  refresh();
};
//人员管理
const userData = ref({});
const userVisible = ref(false);
const userApi = ref("");
const handleUesrManage = async (val) => {
  const { data } = await getUsersList({ id: val.id });
  userData.value = {
    userData: data?.user_ids || [],
    roleName: val.name,
    parmas: { role_id: val.id },
  };
  userApi.value = setUser;
  userVisible.value = true;
};
//删除
const handleDelete = () => {
  let records = tableRef?.value.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除
        <span class="text-[#3366F1] px-[4px]">{ids?.length || 0}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await deleteR({ ids });
          if (code !== 200) return ElMessage.success(message);
          ElMessage.success("删除成功!");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const roleRef = ref();
const optionsType = ref("");
// const roleData = ref({});
//新增编辑
const handleAdd = async (id) => {
  let roleObj = {}
  optionsType.value = id ? "修改" : "新增";
  if (id) {
    const { data } = await detail({ id });
    roleObj = data;
  }
  roleRef.value.open(roleObj);
};
//复制
const handleCopy = async () => {
  let records = tableRef?.value.$table.getCheckboxRecords();
  if (!records?.length) return ElMessage.warning("请至少选择一条数据!");
  const ids = records.map((item) => item.id);
  if (ids?.length > 1) return ElMessage.warning("请选择一条数据!");
  optionsType.value = "复制";
  const { data } = await detail({ id: ids[0] });
  // roleData.value = data;
  let roleObj = data;
  roleRef.value.open(roleObj);
};

const roleConfirm = async (obj) => {
  const { id, name, status } = obj.role;
  switch (optionsType.value) {
    case "新增":
      try {
        const { code, message } = await create({ ...obj });
        if (code !== 200) return ElMessage.error(message);
        ElMessage.success("新增成功！");
        refresh();
        roleRef.value.cancel();
      } catch (error) {
        roleRef.value.data.loading.saveEnable = false;
        roleRef.value.data.loading.save = false;
      }
      break;
    case "复制":
      try {
        const { code, message } = await copyAdd({
          role: { name, status },
          role_owner: obj.role_owner,
        });
        if (code !== 200) return ElMessage.error(message);
        ElMessage.success("复制成功！");
        refresh();
        roleRef.value.cancel();
      } catch (error) {
        roleRef.value.data.loading.saveEnable = false;
        roleRef.value.data.loading.save = false;
      }
      break;
    case "修改":
      try {
        const { code, message } = await updateRole({ ...obj });
        if (code !== 200) return ElMessage.error(message);
        ElMessage.success("修改成功！");
        refresh();
        roleRef.value.cancel();
      } catch (error) {
        roleRef.value.data.loading.saveEnable = false;
        roleRef.value.data.loading.save = false;
      }
      break;
  }
};
const logRef = ref();
const handleLog = (id) => {
  logRef.value.open(id);
};
//更新表格数据
const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};
</script>
